package com.glory.good_dark.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.good_dark.R;
import com.glory.good_dark.adapter.CheckTableListAdapter;
import com.glory.good_dark.application.App;
import com.glory.good_dark.entity.CheckDescListEntity;
import com.glory.good_dark.entity.CheckState;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: CheckDescListActivity
 * Author: XJH
 * Date: 2020/4/2 16:05
 * Description: 交接班检
 * History:
 */
public class CheckDescListActivity extends BaseProjectActivity {
    @BindView(R.id.EQPID_Txt)
    TextView EQPIDTxt;
    @BindView(R.id.tvCheckState)
    TextView tvCheckState;
    @BindView(R.id.ivCheckStateListArrow)
    ImageView ivCheckStateListArrow;
    @BindView(R.id.flCheckStateList)
    FrameLayout flCheckStateList;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.ivStartTimeListArrow)
    ImageView ivStartTimeListArrow;
    @BindView(R.id.flStartTimeList)
    FrameLayout flStartTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeListArrow)
    ImageView ivEndTimeListArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.btnAdd)
    Button btnAdd;
    @BindView(R.id.btnSearch)
    Button btnSearch;
    @BindView(R.id.mtl_Lay)
    LinearLayout mtlLay;
    @BindView(R.id.rvCheckList)
    RecyclerView rvCheckList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private String name;
    private String checkType = "执行中";
    private String beginTime = "";
    private String endTime = "";
    private List<String> checkStates;
    private CustomDatePicker mDatePicker;
    boolean isBegin;
    private FreeUI_GeneralPop statePop;
    private CheckTableListAdapter checkTableListAdapter;
    private String type;
    private String firstInspection = "PDAFirstInspection";//首检
    private String handoverCheck = "PDAHandoverCheck";//交接班检
    private String samplingInspection = "PDASamplingInspection";//抽检
    private String method = "";


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_check_desc;
    }

    @Override
    protected void initView() {
        name = getIntent().getExtras().getString("name");
        type = getIntent().getExtras().getString("type");
        switch (name){
            case "首检":
                method = firstInspection;
                break;
            case "交接班检":
                method = handoverCheck;
                break;
            case "抽检":
                method = samplingInspection;
                break;
        }

        beginTime = FreeApi_DateUtils.getNowStringDate("yyyy/MM/dd HH:mm");
        endTime = FreeApi_DateUtils.getNowStringDate("yyyy/MM/dd HH:mm");
        tvCheckState.setText(checkType);
        tvStartTime.setText(beginTime);
        tvEndTime.setText(endTime);
        EQPIDTxt.setText(App.EQPID);
        checkStates = new ArrayList<>();
        initDatePicker();
        initRecyclerView(rvCheckList,this);
        checkTableListAdapter = new CheckTableListAdapter(null);
        checkTableListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        checkTableListAdapter.isFirstOnly(true);
        rvCheckList.setNestedScrollingEnabled(false);
        rvCheckList.setAdapter(checkTableListAdapter);
        checkTableListAdapter.setDeleteClickListener(new CheckTableListAdapter.OnDeleteClickListener() {
            @Override
            public void onDelete(View v, String s,int position) {
                FreeUI_EntityCallBack<BaseEntity<JsonObject>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<JsonObject>>
                        (new TypeToken<BaseEntity<JsonObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess
                            (final Response<BaseEntity<JsonObject>> response) {
                        if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
                            checkTableListAdapter.remove(position);
                            checkTableListAdapter.notifyDataSetChanged();
                            showToast("删除成功",true);
                        }
                    }

                    @Override
                    public void onError
                            (Response<BaseEntity<JsonObject>> response) {
                        super.onError(response);
                        loadError(response.getException(), "PDADeleteCheckInfo");
                    }
                };
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("ID",s);
                NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDADeleteCheckInfo", jsonObject);
            }
        });
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginTime = FreeApi_DateUtils.long2Str(timestamp, true);
                tvStartTime.setText(beginTime);
            } else {
                endTime = FreeApi_DateUtils.long2Str(timestamp, true);
                tvEndTime.setText(endTime);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(true);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    @Override
    protected void initData() {
//        String ss = "{\n" +
//                "    \"data\":{\n" +
//                "        \"HEADER\":{\n" +
//                "            \"MACHINENAME\":\"PDA-MT9001\",\n" +
//                "            \"MESSAGENAME\":\"PDAHandoverCheck\",\n" +
//                "            \"TRANSACTIONID\":\"c5e5e318-389d-4c39-b914-e4c10ba519d4\",\n" +
//                "            \"EVENTTIME\":\"2019-03-16 16:28:59.585\"\n" +
//                "        },\n" +
//                "        \"BODY\":{\n" +
//                "            \"EQP_ID\":\"LC128\",\n" +
//                "            \"CHECK_STATE_LIST\":[\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"计划中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"待执行\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"执行中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"待确定\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"确定中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"执行结束\"\n" +
//                "                }\n" +
//                "            ],\n" +
//                "            \"CHECK_TABLE_LIST\":[\n" +
//                "                {\n" +
//                "                    \"ID\":9292122,\n" +
//                "                    \"DESCRIPTION\":null,\n" +
//                "                    \"CREATOR\":\"wuwanhai\",\n" +
//                "                    \"CREATED_TIME\":\"2020-03-28T23:43:31\",\n" +
//                "                    \"UPDATOR\":null,\n" +
//                "                    \"UPDATED_TIME\":null,\n" +
//                "                    \"CHECK_NAME\":\"NXP设备的月度保养列表\",\n" +
//                "                    \"CHECK_ID\":\"f690d7b2-aa42-4b29-a465-b585b72f91f3\",\n" +
//                "                    \"EQP_NO\":\"TEST03\",\n" +
//                "                    \"CHECK_STATE\":\"执行中\",\n" +
//                "                    \"COMPLETION_TIME\":null,\n" +
//                "                    \"OPERATOR\":null,\n" +
//                "                    \"PLAN_CHECK_STIME\":null,\n" +
//                "                    \"PLAN_CHECK_ETIME\":null,\n" +
//                "                    \"MAX_DELAY_DAYS\":null,\n" +
//                "                    \"REMIND_TIME\":null,\n" +
//                "                    \"REMIND_ALARM\":null,\n" +
//                "                    \"PM_CHECK_CLASS\":\"交接班检\",\n" +
//                "                    \"CONFIRMEDBY\":null,\n" +
//                "                    \"START_CHECK_TIME\":\"2020-03-29T23:43:31\",\n" +
//                "                    \"ISNEED_PM_STS\":null,\n" +
//                "                    \"CHECK_NAME_CONFIRM\":null,\n" +
//                "                    \"PM_SCHEDULE_NAME\":null,\n" +
//                "                    \"CONFIRMED_GUID\":null\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        },\n" +
//                "        \"RETURN\":{\n" +
//                "            \"RETURNCODE\":\"0\",\n" +
//                "            \"RETURNMESSAGE\":\"\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//        BaseEntity<CheckDescListEntity> bean = (new Gson()).fromJson(ss, new TypeToken<BaseEntity<CheckDescListEntity>>() {}.getType());
//        checkStates.clear();
//        List<CheckState> check_state_list = bean.getData().getBody().getCHECK_STATE_LIST();
//        for (CheckState state : check_state_list){
//            checkStates.add(state.getCHECK_STATE_NAME());
//        }
//
//        checkTableListAdapter.getData().clear();
//        checkTableListAdapter.setNewData(bean.getData().getBody().getCHECK_TABLE_LIST());
        FreeUI_EntityCallBack<BaseEntity<CheckDescListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<CheckDescListEntity>>
                (new TypeToken<BaseEntity<CheckDescListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<CheckDescListEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
                    checkStates.clear();
                    List<CheckState> check_state_list = response.body().getData().getBody().getCHECK_STATE_LIST();
                    for (CheckState state : check_state_list){
                        checkStates.add(state.getCHECK_STATE_NAME());
                    }

                    checkTableListAdapter.getData().clear();
                    checkTableListAdapter.setNewData(response.body().getData().getBody().getCHECK_TABLE_LIST());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<CheckDescListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAHandoverCheck");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQP_ID",App.EQPID);
        map.addProperty("CHECK_STATE",checkType);
        map.addProperty("PLAN_CHECK_STIME",beginTime + ":00");
        map.addProperty("PLAN_CHECK_ETIME",endTime + ":59");
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, method, map);
}

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(name);
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
    }

    @OnClick({R.id.flCheckStateList, R.id.flStartTimeList, R.id.flEndTimeList, R.id.btnAdd, R.id.btnSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flCheckStateList:
                if (checkStates.size() <= 0){
                    showToast("未获取到状态列表",false);
                    return;
                }
                if (statePop != null) {
                    if (statePop.isShowing()) {
                        statePop.dismiss();
                    }
                } else {

                    statePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCheckStateList.getWidth(), checkStates, ivCheckStateListArrow, (code, i) -> {
                        tvCheckState.setText(code);
                        checkType = code;
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivCheckStateListArrow);
                statePop.showAsDropDown(flCheckStateList, 0, 0);
                break;
            case R.id.flStartTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.btnAdd:
                Bundle bundle = new Bundle();
                bundle.putString("name",name);
                bundle.putString("type",type);
                FreeApi_Utils.skipWithExtraIntent("header", bundle,CheckDescListActivity.this, AddCheckActivity.class);
                break;
            case R.id.btnSearch:
                initData();
                break;
        }
    }

    @Override
    protected void EQPReplaceSuccess(int tag, String content) {

    }
}
